package handler

import (
	"github.com/gin-gonic/gin"
	"home-bank/common/format_time"
	"home-bank/common/response"
	"home-bank/service/something/api/internal/types"
	"home-bank/service/something/model"
)

func CreateSomething(c *gin.Context) {
	defer func() {
		err := recover()
		if err != nil {
			response.JsonResponse(c, response.FailCode, nil, err)
		}
	}()

	var params types.CreateSomethingRequest

	if c.BindJSON(&params) != nil {
		panic("something创建参数有误")
	}

	curr_time := format_time.GetCurrTime()
	sth := &model.Something{
		Name:        params.Name,
		CategoryId:  params.CategoryId,
		ContainerId: params.ContainerId,
		CreateTime:  curr_time,
		UpdateTime:  curr_time,
		IsDelete:    model.NotDeletedStatus,
	}

	err := sth.Insert()

	if err != nil {
		panic("something创建失败")
	}

	response.JsonResponse(c, response.SuccessCode, true, "something创建成功")
}

func DeleteSomething(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			response.JsonResponse(c, response.FailCode, nil, err)
		}
	}()

	var params types.DeleteSomethingRequest

	if c.BindJSON(&params) != nil {
		panic("something删除参数有误")
	}

	curr_time := format_time.GetCurrTime()
	sth := &model.Something{
		Id:         params.Id,
		IsDelete:   model.DeletedStatus,
		UpdateTime: curr_time,
	}

	//逻辑删除
	if sth.Update() != nil {
		panic("something删除失败")
	}

	response.JsonResponse(c, response.SuccessCode, true, "something删除成功")
}

func GetSomethingList(c *gin.Context) {
	defer func() {
		err := recover()
		if err != nil {
			response.JsonResponse(c, response.FailCode, nil, err)
		}
	}()

	var params types.GetSomethingListRequest

	err := c.BindJSON(&params)

	if err != nil {
		panic(err.Error())
	}

	sth := &model.Something{
		IsDelete: model.NotDeletedStatus,
	}
	if params.Name != "" {
		sth.Name = params.Name
	}

	if params.ContainerId != 0 {
		sth.ContainerId = params.ContainerId
	}

	if params.CategoryId != 0 {
		sth.CategoryId = params.CategoryId
	}

	if params.Page == 0 {
		params.Page = 1
	}

	if params.PageSize == 0 {
		params.PageSize = 20
	}

	somethingList, total, _ := sth.GetList(params.Page, params.PageSize)

	res := types.GetSomethingListResponse{
		List:     somethingList,
		Page:     params.Page,
		PageSize: params.PageSize,
		Total:    total,
	}

	response.JsonResponse(c, response.SuccessCode, res, "success")
}

func UpdateSomething(c *gin.Context) {
	defer func() {
		err := recover()
		if err != nil {
			response.JsonResponse(c, response.FailCode, false, err)
		}
	}()

	var params types.UpdateSomethingRequest

	err := c.BindJSON(&params)

	if err != nil {
		panic(err.Error())
	}

	sth := &model.Something{
		Id: params.Id,
	}

	if params.Name != "" {
		sth.Name = params.Name
	}

	if params.CategoryId != 0 {
		sth.CategoryId = params.CategoryId
	}

	if params.ContainerId != 0 {
		sth.ContainerId = params.ContainerId
	}

	if sth.Update() != nil {
		panic("something修改失败")
	}

	response.JsonResponse(c, response.SuccessCode, true, "something修改成功")
}
